package com.moive.news.tqnewsapplication.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.adapter.MyProAdapter;
import com.moive.news.tqnewsapplication.adapter.SearchAdapter;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.MyProInfo;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/12/26.
 */

public class PersonDetilsActivity extends BaseActivity implements SecondXListView.IXListViewListener, View.OnClickListener {
    @BindView(R.id.pub_all_listview)
    SecondXListView pubAllListview;
    @BindView(R.id.hiss_back)
    ImageView hissBack;
    Button persondetilsButton;
    TextView personGuanzhu;
    TextView personFans;
    LinearLayout personMainRootLayout;
    TextView persionName;
    CircleImageView persionUserImg;
    private int page = 1;
    private Gson gson = new Gson();
    MyProAdapter adapter;
    List<MyProInfo.DataBean> list = new ArrayList<>();
    private String userid = "", user_img = "", user_name = "";
  private int type=0;
    private boolean isguanzhu=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_persiondetils);
        ButterKnife.bind(this);
        init();
    }
    private void init() {
        View view= LayoutInflater.from(PersonDetilsActivity.this).inflate(R.layout.persiondetils_header,null,false);
        persondetilsButton=view.findViewById(R.id.persondetils_button);
        personGuanzhu=view.findViewById(R.id.person_guanzhu);
        personFans=view.findViewById(R.id.person_fans);
        personMainRootLayout=view.findViewById(R.id.person_main_root_layout);
        persionName=view.findViewById(R.id.persion_name);
        persionUserImg=view.findViewById(R.id.persion_user_img);
        Intent intent = getIntent();
        if (intent != null) {
            userid = intent.getStringExtra("id");
            user_img = intent.getStringExtra("user_img");
            user_name = intent.getStringExtra("user_name");
            isguanzhu=intent.getBooleanExtra("isguanzhu",false);
            if (isguanzhu==true){
                persondetilsButton.setText("已关注");
            }else {
                persondetilsButton.setText("关注");
            }
            persionName.setText(user_name);
            Glide.with(PersonDetilsActivity.this)
                    .load(user_img)
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.drawable.icon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(persionUserImg);
        }
        adapter = new MyProAdapter(PersonDetilsActivity.this);
        pubAllListview.setAdapter(adapter);
        pubAllListview.setXListViewListener(this);
        pubAllListview.setPullLoadEnable(true);
        pubAllListview.addHeaderView(view);
        persondetilsButton.setOnClickListener(this);
        search();
        getdata();
        hissBack.setOnClickListener(v -> finish());
    }
    @Override
    public void onRefresh() {
        page = 1;
        list.clear();
        getdata();
        adapter.notifyDataSetChanged();
        stopOnLoad();
    }
    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getdata();
                adapter.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }
    private void stopOnLoad() {
        pubAllListview.stopRefresh();
        pubAllListview.stopLoadMore();
        pubAllListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.persondetils_button:
                if (isguanzhu==true){
                    delteguanzhu(userid);
                }else {
                    gguanzhu(userid);
                }
                break;
        }
    }
    private void search() {
        OkHttpUtils.post()
                .url(BaseApi.SRARCH_FANS)
                .addParams("userID", userid)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.e(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String follow = jsonObject1.getString("follow");
                        String followed = jsonObject1.getString("followed");
                        personGuanzhu.setText(follow);
                        personFans.setText(followed);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //加关注
    private void gguanzhu( String followID) {
        OkHttpUtils.post()
                .url(BaseApi.GUANZHU_ONE)
                .addParams("token", PreferenceUtil.getString("token", ""))
                .addParams("followID", followID)
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e("lidaming", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i("lidaming", response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        persondetilsButton.setText("已关注");
                    isguanzhu=true;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //取消关注
    private void delteguanzhu(String followID) {
        OkHttpUtils.post()
                .url(BaseApi.UN_GUANZHU)
                .addParams("token", PreferenceUtil.getString("token", ""))
                .addParams("followID", followID)
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e("lidaming", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i("lidaming", response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        persondetilsButton.setText("关注");
                       isguanzhu=false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void getdata() {
        OkHttpUtils.post()
                .url(BaseApi.MYDYNA)
                .addParams("userID", userid)
                .addParams("rows", "10")
                .addParams("page", page + "")
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                            MyProInfo.DataBean dataBean = gson.fromJson(jsonObject1 + "", MyProInfo.DataBean.class);
                            list.add(dataBean);
                        }if (jsonArray.length()==0){
                            ToastUtils.ShortToast("没有更多数据了！");
                        }
                        adapter.addItems(list);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
